Dart Future
创建 Future
Future 是对 EventQueue 中事件的上层封装。Future 有多种创建方式。
默认构造函数
方法实现:
factory Future(FutureOr<T> computation()) {
_Future<T> result = new _Future<T>();
Timer.run(() {
try {
result._complete(computation());
} catch (e, s) {
_completeWithErrorCallback(result, e, s);
}
});
return result;
}
其中:
- 通过 Timer.run 调度
- 插入 EventQueue
Future.microtask
方法签名:
factory Future.microtask(FutureOr<T> computation()) {
内部通过 scheduleMicrotask 插入微任务队列。
Future.sync
方法签名:
factory Future.sync(FutureOr<T> computation()) {
try {
var result = computation();
if (result is Future<T>) {
return result;
} else {
return new _Future<T>.value(result as dynamic);
}
} catch (error, stackTrace) {
……
}
}
其中:
- 如果是同步结果直接运行并返回结果
- 如果是返回一个 Future,则返回 Future
Future.value
在微任务队列中调度。
Future.delayed
基于 Timer 延时执行,插入任务队列。
then
then 用于 future 链式调用。Future 执行完成后,会对后面的 then 进行同步链式调用。then 就是回调,立即同步执行。
超时如何处理
假设有一个 HTTP 请求,但是超时了:
dynamic getSomething(String url) async {
try {
var response = await http.get(url).timeout(new Duration(seconds: 30));
return JSON.decode(response.body);
} catch (_) {
return null;
}
}
这里面有两个 Future,一个是 http.get,一个是 JSON.decode。如果请求卡了30s,超时后抛出一个 TimeoutException。这时候的行为是什么?
对于 Future 而言,当没有对他的引用时,会自动被垃圾回收。
参考资料: